<template>
  <div class="project-members">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="!project" class="empty-state">
      <el-empty description="项目不存在" />
    </div>
    
    <div v-else>
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-left">
          <el-button @click="$router.back()">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1>{{ project.name }} - 成员管理</h1>
        </div>
        
        <div class="header-right">
          <!-- 添加成员按钮已移至成员卡片头部 -->
        </div>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <el-card class="search-card">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="关键词">
              <el-input
                v-model="searchForm.keyWord"
                placeholder="搜索成员姓名或账号..."
                style="width: 250px;"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="角色">
              <el-select
                v-model="searchForm.role"
                placeholder="选择角色"
                style="width: 150px;"
                clearable
              >
                <el-option label="全部" :value="undefined" />
                <el-option label="项目负责人" value="owner" />
                <el-option label="开发人员" value="developer" />
                <el-option label="测试人员" value="tester" />
                <el-option label="观察者" value="observer" />
              </el-select>
            </el-form-item>
            
            
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 成员列表 -->
      <el-card class="members-card">
        <template #header>
          <div class="card-header">
            <span>项目成员 ({{ filteredMembers.length }})</span>
            <div class="header-actions">
              <el-button type="primary" size="small" @click="showAddMemberDialog = true">
                <el-icon><Plus /></el-icon>
                添加成员
              </el-button>
            </div>
          </div>
        </template>
        
        <div v-if="project.members?.length === 0" class="empty-state">
          <el-empty description="暂无成员">
            <el-button type="primary" @click="showAddMemberDialog = true">
              添加第一个成员
            </el-button>
          </el-empty>
        </div>
        
        <div v-else-if="filteredMembers.length === 0" class="empty-state">
          <el-empty description="没有找到匹配的成员">
            <el-button @click="handleReset">清除筛选</el-button>
          </el-empty>
        </div>
        
        <div v-else class="members-grid">
          <el-card
            v-for="member in filteredMembers"
            :key="member.id"
            class="member-card"
            shadow="hover"
          >
            <div class="member-header">
              <el-avatar :size="50" class="member-avatar">
                {{ member.name?.charAt(0) }}
              </el-avatar>
              <div class="member-basic-info">
                <h4 class="member-name">{{ member.name }}</h4>
                <p class="member-account">{{ member.account }}</p>
                <el-tag :type="getRoleType(member.role)" size="small">
                  {{ getRoleText(member.role) }}
                </el-tag>
              </div>
            </div>
            
            <div class="member-details">
              <div v-if="member.deptName" class="detail-item">
                <el-icon class="detail-icon"><OfficeBuilding /></el-icon>
                <span class="detail-label">部门：</span>
                <span class="detail-value">{{ member.deptName }}</span>
              </div>
              
              <div v-if="member.email" class="detail-item">
                <el-icon class="detail-icon"><Message /></el-icon>
                <span class="detail-label">邮箱：</span>
                <span class="detail-value">{{ member.email }}</span>
              </div>
              
              <div v-if="member.phone" class="detail-item">
                <el-icon class="detail-icon"><Phone /></el-icon>
                <span class="detail-label">手机：</span>
                <span class="detail-value">{{ member.phone }}</span>
              </div>
              
              <div class="detail-item">
                <el-icon class="detail-icon"><Clock /></el-icon>
                <span class="detail-label">加入时间：</span>
                <span class="detail-value">{{ formatDate(member.createdAt) }}</span>
              </div>
            </div>
            
            <div class="member-actions">
              <el-button type="primary" size="small" @click="editMember(member)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="removeMember(member)">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>
          </el-card>
        </div>
      </el-card>
    </div>
    
    <!-- 添加/编辑成员对话框 -->
    <el-dialog
      v-model="showAddMemberDialog"
      :title="editingMember ? '编辑成员' : '添加成员'"
      width="500px"
      @close="resetMemberForm"
    >
      <el-form
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberRules"
        label-width="80px"
      >
        <el-form-item v-if="!editingMember" label="选择用户" prop="userId">
          <el-tree-select
            v-model="memberForm.userId"
            :data="userTreeOptions"
            :props="userTreeSelectProps"
            placeholder="请选择用户"
            clearable
            check-strictly
            :render-after-expand="false"
            :show-checkbox="false"
            :default-expand-all="false"
            :expand-on-click-node="false"
            style="width: 100%"
            @change="handleUserSelect"
          />
        </el-form-item>
        
        <el-form-item v-if="editingMember" label="用户信息">
          <div class="user-info-display">
            <span>{{ memberForm.name }} ({{ memberForm.account }})</span>
          </div>
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="memberForm.role" placeholder="请选择角色">
            <el-option label="项目负责人" value="owner" />
            <el-option label="开发人员" value="developer" />
            <el-option label="测试人员" value="tester" />
            <el-option label="观察者" value="observer" />
            <el-option label="成员" value="member" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddMemberDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleMemberSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, OfficeBuilding, Message, Phone, Clock } from '@element-plus/icons-vue'
import { getProjectInfo, type Project } from '@/api/project'
import { addProjectMembers, updateProjectMember, deleteProjectMember, getProjectMembers, type ProjectMember } from '@/api/projectMember'
import { getUserList, type User } from '@/api/user'
import { getDeptList, type Dept } from '@/api/dept'

const route = useRoute()

const projectId = computed(() => parseInt(route.params.id as string))

const loading = ref(false)
const submitting = ref(false)
const showAddMemberDialog = ref(false)

const project = ref<Project | null>(null)
const editingMember = ref<ProjectMember | null>(null)
const users = ref<User[]>([])
const departments = ref<Dept[]>([])

const searchForm = reactive({
  keyWord: '',
  role: undefined as string | undefined
})

const memberFormRef = ref<FormInstance>()
const memberForm = reactive({
  userId: null as number | null,
  account: '',
  name: '',
  role: '',
  projectId: projectId.value
})

const memberRules: FormRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const fetchProject = async () => {
  loading.value = true
  try {
    const result = await getProjectInfo(projectId.value)
    project.value = result.data
    if (project.value) {
      // 获取项目成员
      await fetchProjectMembers()
    }
  } catch (error) {
    ElMessage.error('获取项目信息失败')
  } finally {
    loading.value = false
  }
}

const fetchProjectMembers = async () => {
  try {
    const result = await getProjectMembers(projectId.value)
    if (project.value) {
      project.value.members = result.data || []
    }
  } catch (error) {
    ElMessage.error('获取项目成员失败')
  }
}

const fetchUsers = async () => {
  try {
    const result = await getUserList({
      pageDto: { pageNumber: 1, pageSize: 1000 }
    })
    users.value = result.data.items
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

const fetchDepartments = async () => {
  try {
    const result = await getDeptList({
      pageDto: { pageNumber: 1, pageSize: 1000 }
    })
    departments.value = result.data.items
  } catch (error) {
    ElMessage.error('获取部门列表失败')
  }
}

// 构建用户树形结构
const buildUserTree = (users: User[], depts: Dept[]) => {
  const deptMap = new Map<string, any>()
  const rootDepts: any[] = []
  
  // 创建部门映射
  depts.forEach(dept => {
    deptMap.set(dept.deptCode, {
      id: dept.id,
      deptName: dept.deptName,
      deptCode: dept.deptCode,
      parentDeptCode: dept.parentDeptCode,
      children: []
    })
  })
  
  // 构建部门树形结构
  depts.forEach(dept => {
    const deptNode = deptMap.get(dept.deptCode)!
    if (dept.parentDeptCode) {
      const parent = deptMap.get(dept.parentDeptCode)
      if (parent) {
        parent.children.push(deptNode)
      } else {
        rootDepts.push(deptNode)
      }
    } else {
      rootDepts.push(deptNode)
    }
  })
  
  // 将用户添加到对应部门
  users.forEach(user => {
    const deptNode = deptMap.get(user.deptCode)
    if (deptNode) {
      deptNode.children.push({
        id: user.id,
        userId: user.id,
        account: user.account,
        name: user.name,
        deptName: user.name,
        deptCode: user.deptCode,
        isUser: true
      })
    }
  })
  
  return rootDepts
}

// 用户树形选择器配置
const userTreeSelectProps = {
  children: 'children',
  label: 'deptName',
  value: 'userId',
  disabled: (data: any) => !data.isUser // 只有用户节点可以选择
}

// 用户树形选项
const userTreeOptions = computed(() => {
  return buildUserTree(users.value, departments.value)
})

const resetMemberForm = () => {
  editingMember.value = null
  memberForm.userId = null
  memberForm.account = ''
  memberForm.name = ''
  memberForm.projectId = projectId.value
  memberForm.role = ''
  memberFormRef.value?.resetFields()
}

const handleUserSelect = (userId: number) => {
  const user = users.value.find(u => u.id === userId)
  if (user) {
    memberForm.account = user.account
    memberForm.name = user.name
  }
}

const editMember = (member: ProjectMember) => {
  editingMember.value = member
  memberForm.userId = member.userId || null
  memberForm.account = member.account
  memberForm.name = member.name
  memberForm.role = member.role
  memberForm.projectId = member.projectId
  showAddMemberDialog.value = true
}

const removeMember = async (member: ProjectMember) => {
  try {
    await ElMessageBox.confirm('确定要移除这个成员吗？', '确认移除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProjectMember(member.id)
    ElMessage.success('移除成功')
    fetchProject()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败')
    }
  }
}

const handleMemberSubmit = async () => {
  if (!memberFormRef.value) return
  
  try {
    const valid = await memberFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    if (editingMember.value) {
      // 更新成员角色
      const updateData = {
        ...editingMember.value,
        role: memberForm.role
      }
      await updateProjectMember(updateData)
      ElMessage.success('更新成功')
    } else {
      // 添加新成员
      const newMember: ProjectMember = {
        id: 0,
        userId: memberForm.userId!,
        account: memberForm.account,
        projectId: projectId.value,
        name: memberForm.name,
        role: memberForm.role,
        createdAt: new Date().toISOString()
      }
      await addProjectMembers({
        projectId: projectId.value,
        members: [newMember]
      })
      ElMessage.success('添加成功')
    }
    
    showAddMemberDialog.value = false
    await fetchProjectMembers()
  } catch (error) {
    ElMessage.error(editingMember.value ? '更新失败' : '添加失败')
  } finally {
    submitting.value = false
  }
}

const getRoleType = (role: string) => {
  const roleTypes: Record<string, string> = {
    owner: 'danger',
    developer: 'primary',
    tester: 'warning',
    observer: 'info'
  }
  return roleTypes[role] || 'info'
}

const getRoleText = (role: string) => {
  const roleTexts: Record<string, string> = {
    owner: '项目负责人',
    developer: '开发人员',
    tester: '测试人员',
    observer: '观察者'
  }
  return roleTexts[role] || role
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 筛选后的成员列表
const filteredMembers = computed(() => {
  if (!project.value?.members) return []
  
  let result = project.value.members

  // 按关键词筛选
  if (searchForm.keyWord) {
    const keyword = searchForm.keyWord.toLowerCase()
    result = result.filter(member => 
      member.name?.toLowerCase().includes(keyword) ||
      member.account?.toLowerCase().includes(keyword) ||
      member.email?.toLowerCase().includes(keyword) ||
      member.phone?.toLowerCase().includes(keyword)
    )
  }

  // 按角色筛选
  if (searchForm.role) {
    result = result.filter(member => member.role === searchForm.role)
  }

  return result
})

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleReset = () => {
  searchForm.keyWord = ''
  searchForm.role = undefined
}

onMounted(() => {
  fetchProject()
  fetchUsers()
  fetchDepartments()
})
</script>

<style scoped lang="scss">
.project-members {
  .loading-container {
    padding: 40px 0;
  }
  
  .empty-state {
    padding: 60px 0;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      h1 {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
    }
  }
  
  .search-card {
    margin-bottom: 24px;
    
    .search-form {
      .el-form {
        margin-bottom: 0;
      }
    }
  }
  
  .members-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      color: #333;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .user-info-display {
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #606266;
      font-size: 14px;
    }
    
    .empty-state {
      padding: 40px 0;
    }
    
    .members-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 20px;
      
      .member-card {
        transition: all 0.3s ease;
        border-radius: 8px;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .member-header {
          display: flex;
          align-items: center;
          gap: 16px;
          margin-bottom: 16px;
          padding-bottom: 16px;
          border-bottom: 1px solid #f0f0f0;
          
          .member-avatar {
            flex-shrink: 0;
          }
          
          .member-basic-info {
            flex: 1;
            
            .member-name {
              font-size: 18px;
              font-weight: 600;
              color: #333;
              margin: 0 0 4px 0;
            }
            
            .member-account {
              font-size: 14px;
              color: #666;
              margin: 0 0 8px 0;
            }
          }
        }
        
        .member-details {
          margin-bottom: 16px;
          
          .detail-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 14px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .detail-icon {
              width: 16px;
              height: 16px;
              margin-right: 8px;
              color: #666;
            }
            
            .detail-label {
              color: #666;
              margin-right: 4px;
              min-width: 60px;
            }
            
            .detail-value {
              color: #333;
              flex: 1;
              word-break: break-all;
            }
          }
        }
        
        .member-actions {
          display: flex;
          gap: 8px;
          justify-content: flex-end;
          padding-top: 16px;
          border-top: 1px solid #f0f0f0;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .members-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    
    .member-card {
      .member-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        
        .member-basic-info {
          .member-name {
            font-size: 16px;
          }
        }
      }
      
      .member-details {
        .detail-item {
          flex-direction: column;
          align-items: flex-start;
          gap: 4px;
          
          .detail-label {
            min-width: auto;
            font-weight: 500;
          }
        }
      }
      
      .member-actions {
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
}

@media (max-width: 480px) {
  .members-grid {
    .member-card {
      .member-actions {
        flex-direction: column;
        
        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>


